﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Media;
using MyMeetup.ViewModels;

namespace MyMeetup
{
    public partial class RadControlsItem1 : PhoneApplicationPage
    {
        public List<Photo> _photos; 
        public RadControlsItem1()
        {
            InitializeComponent();
        }

		protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (_photos == null && State.ContainsKey("CurrentPhotos"))
                _photos = State["CurrentPhotos"] as List<Photo>;

            if (this.NavigationContext.QueryString.ContainsKey("albumId"))
            {
                
                if (this.NavigationContext.QueryString.ContainsKey("url"))
                {
                    string key = this.NavigationContext.QueryString["url"];

                    var viewModel = new PhotoPageViewModel(Convert.ToInt32(this.NavigationContext.QueryString["albumId"]), key);
                    this.DataContext = viewModel;

                    //for (int i=0; i<viewModel.CurrentPhotos.Count; i++)
                    //{
                    //    var photo = viewModel.CurrentPhotos[i];
                    //    if (photo.photo_link == key)
                    //    {
                    //        this.slideView.SelectedItem = photo;
                    //        return;
                    //    }
                    //}
                }

                
            }
        }


        private void SavePhoto(object sender, EventArgs e)
        {
            if (LicenseHelper.IsTrial())
            {
                // show trial page
                NavigationService.Navigate(new Uri("/BuyNow.xaml", UriKind.Relative));
            }
            else
            {


                // Create a filename for JPEG file in isolated storage.
                String tempJPEG = "TempJPEG";

                // Create virtual store and file stream. Check for duplicate tempJPEG files.
                var myStore = IsolatedStorageFile.GetUserStoreForApplication();
                if (myStore.FileExists(tempJPEG))
                {
                    myStore.DeleteFile(tempJPEG);
                }

                IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJPEG);


                // Create a stream out of the sample JPEG file.
                // For [Application Name] in the URI, use the project name that you entered in the previous steps. Also TestImage.jpg is an example,
                //you must enter your JPEG filename if it is different.
                //StreamResourceInfo sri = null;
                Uri uri = new Uri(((Photo)slideView.SelectedItem).photo_link, UriKind.Absolute);
                //sri = Application.GetResourceStream(uri);
                int idx = uri.AbsolutePath.LastIndexOf('/');
                string filename = uri.AbsolutePath.Substring(idx + 1);


                WebClient webClient = new WebClient();
                webClient.OpenReadCompleted += delegate(object sender2, OpenReadCompletedEventArgs e2)
                {
                    try
                    {
                        // Create a new WriteableBitmap object and set it to the JPEG stream.
                        BitmapImage bitmap = new BitmapImage();
                        bitmap.SetSource(e2.Result);
                        WriteableBitmap wb = new WriteableBitmap(bitmap);

                        Extensions.SaveJpeg(wb, myFileStream, wb.PixelWidth,
                                            wb.PixelHeight, 0, 85);
                        myFileStream.Close();

                        // Create a new stream from isolated storage, and save the JPEG file to the media library on Windows Phone.
                        myFileStream = myStore.OpenFile(tempJPEG, FileMode.Open,
                                                        FileAccess.Read);

                        MediaLibrary library = new MediaLibrary();
                        Picture pic = library.SavePicture(filename, myFileStream);
                        myFileStream.Close();
                        Dispatcher.BeginInvoke(
                            () =>
                            MessageBox.Show("Image saved!", "Success",
                                            MessageBoxButton.OK));
                    }
                    catch (Exception ex)
                    {
                        Dispatcher.BeginInvoke(
                            () =>
                            MessageBox.Show("There was an error saving the image."));
                    }

                };
                webClient.OpenReadAsync(uri);

            }

        }
    }
}
